package com.example.zbh.lessona.media;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.VideoView;

import com.example.zbh.lessona.R;

import java.io.IOException;

/**
 * Created by zbh on 15/11/25.
 */
public class MediaActivity extends Activity {
    private SurfaceView surfaceView;
    private SurfaceHolder holder;
    private MediaPlayer player;
    private VideoView videoview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media);
        init();

    }

    private void init() {
        surfaceView = (SurfaceView) findViewById(R.id.video);
        videoview = (VideoView) findViewById(R.id.videoview);
        videoview.setVideoPath("http://otmv.alicdn.com/new/mv_1_0/97/3d/97c1125e8340cbe1c69ee4ce13d1ea3d.mp4");
        videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoview.start();
            }
        });

        holder = surfaceView.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                player = new MediaPlayer();
                try {
                    player.setDataSource("http://otmv.alicdn.com/new/mv_1_0/97/3d/97c1125e8340cbe1c69ee4ce13d1ea3d.mp4");
                    player.setDisplay(holder);
                    player.prepareAsync();//网络流媒体的准备方法
                    //设置准备监听是否准备完毕
                    player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mp.start();//播放视频
                        }
                    });


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (player != null) {
                    if (player.isPlaying()) {
                        player.stop();
                    }
                    player.release();
                    player = null;

                }

            }
        });
    }
}
